package com.zkingsoft.actions.admin;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.constance.Dictionary;
import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.Role;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.EncrypUtil;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.RoleService;
import com.zkingsoft.services.UsersService;

/**
 * @description 企业管理员管理action
 * @author 姜友瑶
 * @email 935090232@qq.com
 * @date 2016-06-26
 */
@Controller
@RequestMapping(value = "admin")
public class CompanyAdminController extends BaseController {

	@Resource
	private UsersService currentService;
	@Resource
	private RoleService roleService;

	/**
	 * 
	 * @Description: 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * @author:姜友瑶
	 * @param page1
	 * @param page2
	 * @return 返回类型 String
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/redirect/{page1}/{page2}")
	public String redirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2) {
		return "admin/" + page1 + "/" + page2;
	}

	@RequestMapping(value = "/redirect/{page1}")
	public String redirect(@PathVariable("page1") String page1) {
		return "admin/" + page1;
	}

	/**
	 * 
	 * @Description: 功能跳转使用的action
	 * @author:姜友瑶
	 * @param page1
	 * @param fnId
	 * @param request
	 * @return 返回类型 String
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/functionRedirect/{page1}/{fnId}")
	public String functionRedirect(@PathVariable("page1") String page1, @PathVariable("fnId") String fnId,
			HttpServletRequest request) {
		request.setAttribute("fnId", fnId);
		return "admin/" + page1;
	}

	/**
	 * 
	 * @Description: 二级功能跳转使用的action，如果功能页面存放在admin文件夹的子文件夹中则需要使用本action
	 * @author:姜友瑶
	 * @param page1
	 * @param page2
	 * @param fnId
	 * @param request
	 * @return 返回类型 String
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/functionRedirect/{page1}/{page2}/{fnId}")
	public String functionRedirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2,
			@PathVariable("fnId") String fnId, HttpServletRequest request) {
		request.setAttribute("fnId", fnId);
		return "admin/" + page1 + "/" + page2;
	}

	/**
	 * 
	 * @Description: 分页查询本公司员工
	 * @author:姜友瑶
	 * @param request
	 * @param admin
	 * @param pageVo
	 * @return 返回类型 AjaxResult
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(HttpServletRequest request, Users admin, PaginationVO pageVo) {
		admin.setIsDeleted(Dictionary.DELETED_N);
		admin.setCompanyId(getMe().getCompanyId());
		admin.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
		return showList(currentService, admin, pageVo);
	}

	/**
	 * 
	 * @Description: 新增或修改管理员
	 * @author:姜友瑶
	 * @param request
	 * @param admin
	 * @return 返回类型 AjaxResult
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/addOrModify")
	@RemoveRequestToken
	public @ResponseBody AjaxResult addOrModify(Users admin) {
		try {
			if (admin.getPassword() != null) {
				admin.setPassword(EncrypUtil.getMD5(admin.getPassword()));
			}
		} catch (UnsupportedEncodingException e) {
			throw new GlobleException("操作失败");
		}
		if (admin.getId() != null) {
			return modify(currentService, admin, "管理员");
		} else {
			admin.setCompanyId(getMe().getCompanyId());
			admin.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
			// 加密密码
			admin.setAccountStatus(Dictionary.ACCOUNT_STATUS_ACTIVATE);
			admin.setRegisterTime(new Date());
			admin.setIsDeleted(Dictionary.DELETED_N);
			return add(currentService, admin, "管理员");
		}
	}

	/**
	 * 
	 * @Description: 修改自己的信息
	 * @author:姜友瑶
	 * @param admin
	 * @return 返回类型 AjaxResult
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/modifyMyInfo")
	public @ResponseBody AjaxResult modifyMyInfo(Users admin) {
		currentService.modify(admin);
		// 更新session信息
		WebUtil.getSession().setAttribute(SystemConstance.LOGIN_KEY, currentService.findById(admin.getId()));
		return modify(currentService, admin, "管理员");
	}

	/**
	 * 
	 * @Description: 删除管理员
	 * @author:姜友瑶
	 * @param keys
	 * @return 返回类型 AjaxResult
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(currentService, keys);
	}

	@RequestMapping(value = "/editForm")
	@SaveRequestToken
	public String editForm(Long id, HttpServletRequest request) {
		Users admin;
		Role role = new Role();
		role.setCompanyId(getMe().getCompanyId());
		List<Role> list = roleService.findByModel(role);
		request.setAttribute("list", list);
		if (id != null) {
			admin = currentService.findById(id);
			request.setAttribute("obj", admin);
		}
		return "admin/admin-form";
	}

	/**
	 * 进入黑名单
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/userEditForm")
	@SaveRequestToken
	public String userEditForm(Long id, HttpServletRequest request) {
		Users admin;
		if (id != null) {
			admin = currentService.findById(id);
			request.setAttribute("obj", admin);
		}
		return "admin/userEdit-form";
	}

	/**
	 * 添加嘿名单
	 * 
	 * @param admin
	 * @return
	 */
	@RequestMapping(value = "/addHmdList")
	@RemoveRequestToken
	public @ResponseBody AjaxResult addHmdList(Users admin) {
		Users users = new Users();
		users.setTel(admin.getTel());
		if ((admin.getId() == null) && (currentService.findByModel(users).size() > 0)) {
			throw new GlobleException("电话已经拉黑");
		} else {
			if (admin.getId() != null) {
				List<Users> list = currentService.findByModel(users);
				if ((list.size() > 0 && !list.get(0).getId().equals(admin.getId())) || list.isEmpty()) {
					return modify(currentService, admin, "黑名单");
				} else {
					throw new GlobleException("电话已经拉黑或存在");
				}
			} else {
				admin.setCompanyId(getMe().getCompanyId());
				admin.setUserType(Dictionary.USER_TYPE_CUSTIMER);
				admin.setAccountStatus(Dictionary.ACCOUNT_STATUS_LOCKED);
				admin.setRegisterTime(new Date());
				admin.setIsDeleted(Dictionary.DELETED_N);
				return add(currentService, admin, "黑名单");
			}
		}

	}

	/**
	 * 跳转到修改个人信息，真正修改的是员工信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/myinfo-list")
	public String myinfo(HttpServletRequest request) {
		return "admin/myinfo-form";
	}

	/**
	 * 进入修改密码界面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/password")
	public String password(HttpServletRequest request) {
		request.setAttribute("obj", currentService.findById(getMe().getId()));
		return "admin/password-form";
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updatePassword")
	public @ResponseBody AjaxResult updatePassword(HttpServletRequest request, String newPassword, String oldPassword) {

		try {
			Users user = getMe();
			// 比较输入的旧密码和老密码是否相等
			if (user.getPassword().equals(EncrypUtil.getMD5(oldPassword))) {
				user.setPassword(EncrypUtil.getMD5(newPassword));
				int i = currentService.modify(user);
				if (i > 0) {
					return new AjaxResult(AjaxResult.STATUS_OK, "login", "密码修改成功 下次登录生效");
				} else {
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "密码修改失败 原因：未知请重试！");
				}
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "密码修改失败 原因：旧密码不正确！");
			}
		} catch (UnsupportedEncodingException e) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "密码修改失败");
		}
	}

	/**
	 * 重置密码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/resetPassword")
	public @ResponseBody AjaxResult resetPassword(HttpServletRequest request) {
		Users user = getMe();
		try {
			user.setPassword(EncrypUtil.getMD5("123"));
			int i = currentService.modify(user);
			if (i > 0) {
				return new AjaxResult(AjaxResult.STATUS_OK, "login", "密码重置成功 下次登录生效");
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "密码重置失败 ");
			}
		} catch (UnsupportedEncodingException e) {

			return new AjaxResult(AjaxResult.STATUS_OK, null, "密码重置失败");
		}
	}

}